  <!-- 业务设置 -->
  <template>
  <div class="main-body">
    <div class="form-body">
      <el-form
        ref="form"
        class="formlayout"
        :model="form"
        label-width="140px"
        label-position="right"
      >
        <el-tabs v-model="activedTab">
          <el-tab-pane label="基础设置" name="sys">
            <div>
              <el-form-item
                class="dccform-line"
                label="小程序名称"
                :prop="getMyKey('appName')"
                required
                :rules="[{required: true, message: '必填'}]"
              >
                <el-input v-model="form[getMyKey('appName')]" clearable placeholder="请输入" maxlength="50"></el-input>
              </el-form-item>
              <el-form-item class="dccform-line" label="商家介绍" :prop="getMyKey('appDesc')">
                <el-input
                  v-model="form[getMyKey('appDesc')]"
                  :autosize="{ minRows: 2, maxRows: 8}"
                  type="textarea"
                  clearable
                  placeholder="请输入"
                  maxlength="50"
                ></el-input>
              </el-form-item>
              <el-form-item class="dccform-line" label="电话" :prop="getMyKey('phone')">
                <el-input v-model="form[getMyKey('phone')]" clearable placeholder="请输入" maxlength="50"></el-input>
              </el-form-item>
              <el-form-item class="dccform-line" label="微信号" :prop="getMyKey('wechat')">
                <el-input v-model="form[getMyKey('wechat')]" clearable placeholder="请输入" maxlength="50"></el-input>
              </el-form-item>
              <el-form-item class="dccform-line" label="配送费用" :prop="getMyKey('deliveryFee')">
                <el-input v-model.number="form[getMyKey('deliveryFee')]" clearable placeholder="请输入" maxlength="5"></el-input>
              </el-form-item>
              <el-form-item class="dccform-line" label="商家地址" :prop="getMyKey('address')">
                <el-input v-model="form[getMyKey('address')]" clearable placeholder="请输入" maxlength="50">
                  <el-button slot="append" icon="el-icon-map-location" @click="showMap"></el-button>
                </el-input>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="固定取货点配置" name="index">
              <el-tag
                :key="tag"
                v-for="tag in placeList"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >{{tag}}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              ></el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New</el-button>
          </el-tab-pane>
        </el-tabs>
        <el-form-item label-width="120px">
          <el-button type="primary" style="width: 120px;margin-top: 50px;" @click="saveHandle">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <MapComp ref="MapCompRef" @finish="changeMap"></MapComp>
  </div>
</template>
    
    <script>
import {
  UploadFile,
  selectFiles,
  DeleteFile,
  getConfig,
  SaveConfig,
  GetFileBase64
} from '@/api'
import MapComp from '@/views/comp/MapComp.vue'
export default {
  components: { MapComp },
  data() {
    return {
      loading: false,
      orgCode: this.$store.getters.orgCode,
      form: {
        [this.getMyKey('appName')]: '',
        [this.getMyKey('appDesc')]: '',
        [this.getMyKey('phone')]: '',
        [this.getMyKey('wechat')]: '',
        [this.getMyKey('address')]: '',
        [this.getMyKey('lng')]: '',
        [this.getMyKey('lat')]: '',
        [this.getMyKey('deliveryFee')]: '',
        [this.getMyKey('placeList')]: ''
      },
      inputValue: '',
      inputVisible: false,
      placeList: [],
      activedTab: 'sys',
      fileList: []
    }
  },
  methods: {
    handleClose(tag) {
      this.placeList.splice(this.placeList.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.placeList.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    changeMap([lng, lat, address]) {
      this.form[this.getMyKey('lng')] = lng
      this.form[this.getMyKey('lat')] = lat
      this.form[this.getMyKey('address')] = address
    },
    showMap() {
      this.$refs.MapCompRef.show(this.form[this.getMyKey('lng')], this.form[this.getMyKey('lat')])
    },
    async saveHandle() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          // // 保存图片
          if (this.fileList.some((d) => d.status !== 'finish')) {
            await this.uploadFiles()
          }
          // 保存
          let data = []
          if (this.placeList && this.placeList.length > 0) {
            this.form[this.getMyKey('placeList')] = this.placeList.join(',')
          }
          for (let k in this.form) {
            data.push({
              code: k,
              value: this.form[k]
            })
          }
          SaveConfig({
            data
          }).then((res) => {
            console.log('SaveConfig', res)
            if (res.code === 20000) {
              this.$store.commit('setAppConfig', this.form)
              this.$message({
                type: 'success',
                message: '保存成功'
              })
            }
          })
        }
      })
    },
    async uploadFiles() {
      return await Promise.all(
        this.fileList
          .filter((d) => d.status != 'finish')
          .map((file) => {
            this.loading = true
            let formData = new FormData()
            formData.append('file', file.raw)
            formData.append('name', file.name)
            formData.append('size', file.size)
            formData.append('type', 'banner')
            formData.append('refId', 'app-banner')
            return UploadFile(formData, (e) => {
              console.log('进度', e)
            }).then((res) => {
              console.log('UploadFile', res)
              this.loading = false
              let ff = this.fileList.find((d) => d.uid === file.uid)
              if (ff) {
                ff.status = 'finish'
              }
            })
          })
      )
    },
    delFile(index) {
      if (this.fileList[index].status === 'finish') {
        DeleteFile({ id: this.fileList[index].id }).then((res) => {
          console.log('DeleteFile', res)
          if (res.code === 20000) {
            this.fileList.splice(index, 1)
          }
        })
      } else {
        this.fileList.splice(index, 1)
      }
    },
    onChange(file) {
      console.log(file)
      if (!this.beforeAvatarUpload(file)) {
        return
      }
      file.url = URL.createObjectURL(file.raw)
      this.fileList.push(file)
    },
    beforeAvatarUpload(file) {
      file.type = file.raw.type
      const isJPG =
        ['image/jpg', 'image/png', 'image/jpeg'].indexOf(file.type) !== -1
      const isLt5M = file.raw.size / 1024 / 1024 < 50
      if (!isJPG) {
        this.$message.error('上传文件只能是 jpg/png格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 50MB!')
      }
      return isJPG && isLt5M
    },
    getMyKey(key) {
      return `${this.orgCode}_${key}`
    },
    loadData() {
      // 加载数据
      getConfig({
        codes: [
          this.getMyKey('appName'),
          this.getMyKey('appDesc'),
          this.getMyKey('phone'),
          this.getMyKey('wechat'),
          this.getMyKey('address'),
          this.getMyKey('lng'),
          this.getMyKey('lat'),
          this.getMyKey('deliveryFee'),
          this.getMyKey('placeList'),
        ].join(',')
      }).then((res) => {
        console.log('getConfig', res)
        if (res.code === 20000) {
          let form = {}
          res.data.forEach((d) => {
            form[d.code] = d.value
          })
          this.form = Object.assign(
            {
              [this.getMyKey('appName')]: '',
              [this.getMyKey('appDesc')]: '',
              [this.getMyKey('phone')]: '',
              [this.getMyKey('wechat')]: '',
              [this.getMyKey('address')]: '',
              [this.getMyKey('lng')]: '',
              [this.getMyKey('lat')]: '',
              [this.getMyKey('deliveryFee')]: '',
              [this.getMyKey('placeList')]: ''
            },
            form
          )
          if (form[this.getMyKey('placeList')]) {
            this.placeList = form[this.getMyKey('placeList')].split(',')
          }
        }
      })
      // 加载图片
      selectFiles({
        refId: 'app-banner',
        type: 'banner'
      }).then(async (res) => {
        console.log('selectFiles', res)
        if (res.code === 20000) {
          this.fileList = await Promise.all(
            res.data.map(async (d) => {
              let dataText = await GetFileBase64({
                id: d.id
              }).then((res) => {
                console.log('GetFileBase64', res)
                return res.code === 20000 && res.data
              })
              return {
                status: 'finish',
                id: d.id,
                uid: d.id,
                url: `data:image/jpeg;base64,${dataText}`
              }
            })
          )
        }
      })
    }
  },
  mounted() {
    this.loadData()
  }
}
</script>
    
<style lang="scss" scoped>
.form-body {
  padding: 30px;
  width: 600px;
  box-sizing: border-box;
  min-height: calc(100vh - 130px);
  text-align: left;
  ::v-deep {
    .el-tag {
      margin-top: 20px;
    }
  }
}
.banner {
  position: relative;
  width: 100%;
  height: 100px;
  border: 1px solid #ccc;
  margin-bottom: 5px;
  box-sizing: border-box;
  overflow: hidden;
  .banner-img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  .el-icon-error {
    position: absolute;
    right: 10px;
    top: 10px;
    font-size: 20px;
    cursor: pointer;
  }
}


.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: auto;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
    